package com.peycard.filter;

import java.io.IOException;
import java.text.ParseException;
import java.util.Collection;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;

import com.peycard.common.PortalUserDTO;
import com.peycard.service.LoginService;

/**
 * Servlet Filter implementation class SpringUserFilter
 */
public class SpringUserFilter implements Filter {

	private static final Logger LOGGER = LoggerFactory
			.getLogger(SpringUserFilter.class);

	/**
	 * Default constructor.
	 */
	public SpringUserFilter() {
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see Filter#destroy()
	 */
	public void destroy() {
		// TODO Auto-generated method stub
	}

	/**
	 * @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
	 */
	public void doFilter(ServletRequest servletRequest,
			ServletResponse servletResponse, FilterChain chain)
			throws IOException, ServletException {
		LOGGER.info("INIT FILTER");
		HttpServletRequest request = (HttpServletRequest) servletRequest;
		HttpSession session = request.getSession();

		PortalUserDTO portalUser = (PortalUserDTO) session
				.getAttribute("userAuthentication");
		String nombre = (String) request.getParameter("j_username");
		LOGGER.info("UserName:" + portalUser);

		if (portalUser == null) {
			LOGGER.info("Reaching authentication details");
			Authentication auth = SecurityContextHolder.getContext()
					.getAuthentication();

			if (auth != null && !auth.getName().equals("anonymousUser")) {
				String springUsername = auth.getName();
				LOGGER.info("UserNameSpringSecurity:" + springUsername);
				Collection<GrantedAuthority> collection = auth.getAuthorities();
				LOGGER.info("Authorities:" + collection);

				if (springUsername != null && !springUsername.isEmpty()) {
					LOGGER.info("Setting attribute");
					try {
						LoginService loginService = new LoginService();
						PortalUserDTO userDTO = loginService
								.loginRequest(springUsername);
						session.setAttribute("userAuthentication", userDTO);
					} catch (ParseException e) {
						LOGGER.error("Error al parsear la peticion");
					}
				}
			}
		}
		chain.doFilter(servletRequest, servletResponse);
	}

	/**
	 * @see Filter#init(FilterConfig)
	 */
	public void init(FilterConfig fConfig) throws ServletException {
	}

}
